package com.hugang.io.inputstreamandoutputstream;

import org.junit.Test;

import java.io.*;

/**
 * 测试FileInputStream和FileOutputStream的使用
 *
 * 结论：
 * 1. 对于文本文件(.txt,.java,.c,.cpp)，使用字符流处理
 * 2. 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,...)，使用字节流处理
 * @author hg
 * @date 2020/6/21 14:13
 */
public class FileInputStreamOutpufStream {

    public static void main(String[] args) {
        long start = System.currentTimeMillis();

        String src = "D:\\BaiduYunDownload\\尚硅谷宋红康Java核心基础_好评如潮\\课件笔记源码资料\\3_软件.zip";
        String dest = "D:\\temp\\3_软件.zip";
        copyFile(src, dest);
        long end = System.currentTimeMillis();
        System.out.println("花费：" + (end - start) + "毫秒");
    }

    @Test
    public void testFileInputStream(){
        FileInputStream fis = null;
        FileOutputStream fow = null;
        try {
            //1、创建File类的对象，指明读入和写出文件
            File srcFile = new File("IO流体系.png");
            File destFile = new File("IO流体系1.png");

            //2、创建输入流和输出流的对象
            fis = new FileInputStream(srcFile);
            fow = new FileOutputStream(destFile);

            //3、读入和写出数据
            byte[] b = new byte[1024];
            int len;
            while ((len = fis.read(b)) != -1) {
                fow.write(b, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4、流的关闭
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void copyFile(String srcPath, String descPath){
        FileInputStream fis = null;
        FileOutputStream fow = null;
        try {
            //1、创建File类的对象，指明读入和写出文件
            File srcFile = new File(srcPath);
            File destFile = new File(descPath);

            //2、创建输入流和输出流的对象
            fis = new FileInputStream(srcFile);
            fow = new FileOutputStream(destFile);

            //3、读入和写出数据
            byte[] b = new byte[1024];
            int len;
            while ((len = fis.read(b)) != -1) {
                fow.write(b, 0, len);
            }
            System.out.println("复制成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4、流的关闭
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
